//
//  TKIMAccountTableViewController.m
//  test2
//
//  Created by TryHone on 17/1/16.
//  Copyright © 2017年 TryHone. All rights reserved.
//

#import "TKIMAccountTableViewController.h"
#import "TKIMAccountModel.h"
#import "TKIMAccountStyle1TableViewCell.h"
#import "TKIMAccountStyle2TableViewCell.h"
#import "TKFriendListSetViewController.h"
#import "TKIMChangeFaceViewController.h"
#import "TKIMAccountHeadView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>

@interface TKIMAccountTableViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UIActionSheetDelegate>

@property(nonatomic,strong) UITableView* tableView;
@property(nonatomic,strong) TKIMAccountHeadView * headView;

@property(nonatomic,strong) UIImagePickerController *imagePicker;
@property(nonatomic,assign) BOOL isAlbum;
@property(nonatomic,strong) TKIMLayerUtils *layerUtils;
//选择的图片
@property(nonatomic,strong) UIImage* seleteimage;//图片

@end

@implementation TKIMAccountTableViewController{

    NSMutableArray* _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置";
    self.tableView.tableFooterView=[UIView new];
    _dataSource = [[NSMutableArray alloc] init];
    [self.headView.face sd_setImageWithURL:[[NSURL alloc] initWithString:[TKIMManager shareInstance].loginUser.thumbPhotoUrl] placeholderImage:TKIMGetImage(@"im_icon_userDefault")];
    self.headView.username.text = [TKIMHelper getShowNameWithUser:[TKIMManager shareInstance].loginUser];
    [self data];//初始化界面数据
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self data];
    [self.view addSubview:self.headView];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
}
-(UITableView*)tableView{

    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,200, self.view.frame.size.width, self.view.frame.size.height-200-49) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.view.backgroundColor=[TKUIHelper colorWithHexString:@"#444a5a"];
        if(IOS7_OR_LATER){
            _tableView.backgroundColor =[TKUIHelper colorWithHexString:@"#F7F7F7"];
        }
        [self.view addSubview:_tableView];
        
    }
    return _tableView;
}

-(void)data{
    
    [_dataSource removeAllObjects];
//    
//    TKIMUser* user=[TKIMManager shareInstance].loginUser;
//
//    TKIMAccountModel * data1 = [[TKIMAccountModel alloc] init];
//    data1.lefttitle = @"头像";
//    data1.rightimagename = user.thumbPhotoUrl?user.thumbPhotoUrl:(user.originalPhotoUrl?user.originalPhotoUrl:@"");
//    
//    TKIMAccountModel * data2 = [[TKIMAccountModel alloc] init];
//    data2.lefttitle = @"姓名";
//    data2.righttitle =[TKIMHelper getShowNameWithUser:user];
    
    TKIMAccountModel * data3 = [[TKIMAccountModel alloc]init];
    data3.lefttitle = @"设置";
    data3.leftimagename = @"img_setting@2x.png";
    
//    [_dataSource addObject:@[data1]];
//    [_dataSource addObject:@[data2]];
    [_dataSource addObject:@[data3]];
    
    
    [_tableView reloadData];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray * data=_dataSource[section];
    return data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell;
    TKIMAccountModel * data = _dataSource[indexPath.section][indexPath.row];
//    if (indexPath.section<2) {
//        TKIMAccountStyle1TableViewCell* cell1 = [TKIMAccountStyle1TableViewCell cellWithTableView:tableView];
//        
//        if (indexPath.section == 0) {
//          [cell1 setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
//        }else{
//            [cell1 setAccessoryType:UITableViewCellAccessoryNone];
//        }
//        
//        cell1.datamodle=data;
//        cell=cell1;
//    }else{
        TKIMAccountStyle2TableViewCell* cell2 = [TKIMAccountStyle2TableViewCell cellWithTableView:tableView];
        cell2.datamodle=data;
        cell=cell2;
//    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return  1;
    }
    return 10;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
      [self section0Seleted:indexPath.row];
    }else if (indexPath.section==1){
      [self section1Seleted:indexPath.row];
    }else if (indexPath.section==2){
      [self section2Seleted:indexPath.row];
    }
}

-(void)section0Seleted:(NSInteger)row{

    switch (row) {
        case 0:
        {
            TKFriendListSetViewController *friendlistset=[[TKFriendListSetViewController alloc] init];
            friendlistset.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:friendlistset animated:YES];
        
        }break;
        default:
            break;
    }
    
}

-(void)section1Seleted:(NSInteger)row{
    
    switch (row) {
        case 0:
        {

            
        }break;
        default:
            break;
    }
    
}
-(void)section2Seleted:(NSInteger)row{
    
    switch (row) {
        case 0:
        {
            TKFriendListSetViewController *friendlistset=[[TKFriendListSetViewController alloc] init];
            friendlistset.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:friendlistset animated:YES];
            
        }break;
        default:
            break;
    }
    
}


-(void)routerEventWithName:(NSString *)eventName userInfo:(NSObject *)userInfo{

    if ([TKIMCHANGEFACE isEqualToString:eventName]) {//换头像
        [self uploadImage];
    }
}

-(void)uploadImage{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"相册上传", nil];
    [sheet showInView:self.view];
    
    
}

-(UIImagePickerController *)imagePicker
{
    if (!_imagePicker)
    {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        if (!_isAlbum)
        {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //设置使用哪个摄像头，这里设置为后置摄像头
            _imagePicker.cameraDevice=UIImagePickerControllerCameraDeviceRear;
        }
        else
        {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing=YES;//允许编辑
        
    }
    return _imagePicker;
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    //获取原始照片
    UIImage *image;
    //如果允许编辑则获得编辑后的照片，否则获取原始照片
    if (self.imagePicker.allowsEditing)
    {
        //获取编辑后的照片
        image=[info objectForKey:UIImagePickerControllerEditedImage];
    }
    else
    {
        //获取原始照片
        image=[info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (image)
    {
        _seleteimage=image;
        [self saveFace:nil];
    }
    
    [self dismissViewControllerAnimated:YES completion:^
     {
         self.imagePicker = nil;
     }];
}


-(void)saveFace:(id)btn{
    [_layerUtils showLoading:YES withLabel:@"正在上传..."];
    UIImage * image = _seleteimage;
    
    
    if (image) {
        
        [[TKIMManager shareInstance] uploadUserHeadImage:image complete:^(NSObject *obj)
         {
             [_layerUtils showLoading:NO];
             [_layerUtils showTip:@"上传成功"];
             [TKIMManager shareInstance].loginUser.thumbPhotoUrl=(NSString*)obj;
             [_headView.face sd_setImageWithURL:[[NSURL alloc] initWithString:(NSString*)obj] placeholderImage:_seleteimage];
             
         } process:^(NSInteger totalBytes, NSInteger bytesWritten)
         {
             NSLog(@"%ld======%ld",totalBytes,bytesWritten);
         } fail:^(NSError *error)
         {
             [_layerUtils showLoading:NO];
             [_layerUtils showTip:@"上传失败"];
         }];
        
        
    }else{
        
        [_layerUtils showLoading:NO];
        [_layerUtils showTip:@"上传失败,请选择图片后重试"];
        
    }
    
    
}




- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^
     {
         self.imagePicker = nil;
     }];
    
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied||![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            [_layerUtils showTip:@"没有调用相机的权限，请到设置中打开"];
            return;
        }
        _isAlbum = NO;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }
    else if(buttonIndex == 1)
    {
        
        _isAlbum = YES;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }
}


#pragma mark--属性

-(TKIMAccountHeadView*)headView{
    if (!_headView) {
        _headView = [[TKIMAccountHeadView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 200)];
    }
    return _headView;

}

@end
